﻿using B.S.DataBase.MyProject.ErrorCode;
using B.S.Traceability.Domain;
using B.S.Traceability.Infrastructure.Interface;
using B.S.Traceability.Read.API.Applicantion.Command.SlaughterInfoCommand;
using MediatR;

namespace B.S.Traceability.Read.API.Applicantion.CommandHandler.SlaughterInfoCommandHandler
{
    public class QuerySlaughterInfoCommandHandler:IRequestHandler<QuerySlaughterInfoCommand,APIResult<List<SU_SlaughterInfo>>>
    {
        private readonly IBaseRepository<SU_SlaughterInfo> slauRep;

        public QuerySlaughterInfoCommandHandler(IBaseRepository<SU_SlaughterInfo> slauRep)
        {
            this.slauRep = slauRep;
        }

        public Task<APIResult<List<SU_SlaughterInfo>>> Handle(QuerySlaughterInfoCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<SU_SlaughterInfo>> result = new APIResult<List<SU_SlaughterInfo>>();
            var firstItem = slauRep.GetAll().Result
                 .Where(x => x.ProductionCode == request.ProductionCode)
                 .OrderByDescending(x => x.SlaughterId)
                 .FirstOrDefault();

            if (firstItem != null)
            {
                result.Code = APIEnum.查询成功;
                result.Msg = APIEnum.查询成功.ToString();
                result.data = new List<SU_SlaughterInfo> { firstItem };
            }
            else
            {
                result.Code = APIEnum.查询失败;
                result.Msg = APIEnum.查询失败.ToString();
                result.data = new List<SU_SlaughterInfo>();
            }
            return Task.FromResult(result);
        }
    }
}
